package com.deng.mina.client;

import com.deng.mina.common.protocol.ProtocolFactory;
import com.deng.mina.common.protocol.ProtocolPack;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import sun.nio.cs.ext.MS874;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @Project
 * @Module
 * @JDK_Vserion 1.8
 * @Author DengLibin
 * @Email dlb@smarthse.cn
 * @Desc Mina客户端
 * @since 2019/9/17 0017 15:44
 */
public class MinaClient {
    private int port = 7080;
    private String host = "127.0.0.1";
    private IoConnector connector;
    private IoHandler handler;
    private IoSession session;
    public MinaClient(){
        init();
    }

    private void init() {
        connector = new NioSocketConnector(4);
        handler = new ClientHandler();
        connector.setConnectTimeoutMillis(3 * 1000);
        DefaultIoFilterChainBuilder filterChain = connector.getFilterChain();
        // 设置过滤器
     /*   filterChain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(
                Charset.forName("UTF-8"),
                LineDelimiter.WINDOWS.getValue(), // 编码器
                LineDelimiter.WINDOWS.getValue() // 解码器
        )));*/

        // 使用自定义编解码器
        filterChain.addLast("codec", new ProtocolCodecFilter(new ProtocolFactory(Charset.forName("UTF-8"))));
        // 设置handler
        connector.setHandler(handler);
    }

    /**
     * 连接
     */
    public void connect(){
        ConnectFuture future = connector.connect(new InetSocketAddress(host, port));
        future.awaitUninterruptibly(); // 等待连接 阻塞
        session = future.getSession();
        write("你好!你好!你好!你好!你好!你好!你好!你好!你好!你好!你好!");
        session.getCloseFuture().awaitUninterruptibly();// 等待关闭连接
        connector.dispose(); // 释放
    }
    private void write(String msg){
      //  session.write(msg); // 发送数据
        for(int i = 0; i < 3; i ++){
            session.write(new ProtocolPack((byte)1, msg+i));
        }

    }
}
